package cn.whdream.datastructure;

import java.util.Scanner;

public class CycleQueueDemo2 {

	public static void main(String[] args) {
		CycleQueue2 queue = new CycleQueue2(4);
		System.out.println("开始对当前队列进行操作");
		boolean loop = true;
		Scanner scanner = new Scanner(System.in);
		while (loop) {
			System.out.println("请输入下列字母进行操作");
			char key = scanner.next().charAt(0);
			try {
				switch (key) {
				case 'a':
					System.out.println("请输入一个数字");
					int num = scanner.nextInt();
					queue.addData(num);
					break;
				case 's':
					System.out.println("当前队列为：");
					queue.showQueue();
					break;
				case 'p':
					System.out.printf("header: %d \n", queue.peekHeader());
					break;
				case 'g':
					System.out.printf("data: %d \n", queue.getData());
					break;
				case 'e':
					loop = false;
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("error:"+e.getMessage());
			}
		}
		System.out.println("程序结束");
	}
}

class CycleQueue2 {
	private int maxSize;
	private int front = 0;//约定为数组的第一个元素
	private int rear = 0;//约定为数组最后一个元素,的后一个元素
	private int[] arr;

	public CycleQueue2(int queueMaxSize) {
		maxSize = queueMaxSize;
		arr = new int[maxSize];
	}

	public void addData(int value) {
		if (isFull()) {
			throw new RuntimeException("当前数据已满，无法添加数据");
		}
		arr[rear] = value;
		rear = (rear+1) % maxSize;
	}

	private boolean isFull() {
		return (rear+1) % maxSize == front;
	}

	public int getData() {
		if (isEmpty()) {
			throw new RuntimeException("当前数据队列为空");
		}
		int temp = arr[front];
		front = (front+1)%maxSize;
		return temp;
	}

	private boolean isEmpty() {
		return rear == front;
	}

	public int peekHeader() {
		if (isEmpty()) {
			throw new RuntimeException("当前数据为空~~~~~");
		}
		return arr[front];
	}

	public void showQueue() {
		if (isEmpty()) {
			throw new RuntimeException("当前数据队列为空");
		}
		int length = getLength();

		for (int i = front; i < front+length;i++ ) {
			System.out.printf("arr[%d]=%d\n", i%maxSize, arr[i%maxSize]);
		}
	}

	private int getLength() {
		
		return (rear+maxSize-front)%maxSize;
	}
}